package com.wangzhixuan.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.List;
import java.util.UUID;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.result.PageInfo;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.model.Bguserinfo;
import com.wangzhixuan.service.IBguserinfoService;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yvan
 * @since 2017-07-30
 */
@Controller
@RequestMapping("/bguserinfo")
public class BguserinfoController extends BaseController {

    @Autowired private IBguserinfoService bguserinfoService;
    
    @GetMapping("/manager")
    public String manager() {
        return "admin/bguserinfo/bguserinfoList";
    }
    
    @PostMapping("/dataGrid")
    @ResponseBody
    public PageInfo dataGrid(Bguserinfo bguserinfo, Integer page, Integer rows, String sort,String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        EntityWrapper<Bguserinfo> ew = new EntityWrapper<Bguserinfo>(new Bguserinfo());
        Page<Bguserinfo> pages = getPage(pageInfo);
        if(StringUtils.isNotBlank(bguserinfo.getName())){
        	ew.like("name", bguserinfo.getName());
        }
        if(StringUtils.isNotBlank(bguserinfo.getTags())){
        	ew.like("tags", bguserinfo.getTags());
        }
        ew.orderBy("id", false);
        pages = bguserinfoService.selectPage(pages, ew);
        pageInfo.setRows(pages.getRecords());
        pageInfo.setTotal(pages.getTotal());
        return pageInfo;
    }
    
    /**
     * 添加页面
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
        return "admin/bguserinfo/bguserinfoAdd";
    }
    
    /**
     * 添加
     * @param 
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(@RequestParam MultipartFile[] myfiles, HttpServletRequest request,@Valid Bguserinfo bguserinfo) {
        try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String pathRoot = request.getSession().getServletContext().getRealPath("");
			SimpleDateFormat sf=new SimpleDateFormat("yyyyMMdd");
			String datestr=sf.format(new Date());
			// 头像
			String path="";
			MultipartFile file = multipartRequest.getFile("pic_manPhoto");
			if(file != null && file.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path="/upload/images/"+datestr+"/"+uuid+"."+imageName;
	            File tFile=new File(pathRoot+path);
	            if(!tFile.getParentFile().exists()){
	            	tFile.mkdirs();
	            }
	            file.transferTo(tFile);  				  
	            bguserinfo.setPreview(path);
			}
			bguserinfo.setAddtime(new Date());
	        bguserinfo.setUpdatetime(new Date());
	        boolean b = bguserinfoService.insert(bguserinfo);
	        if (b) {
	            return renderSuccess("添加成功！");
	        } else {
	            return renderError("添加失败！");
	        }
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return renderError("添加失败！");
    }
    
    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(Integer id) {
        Bguserinfo bguserinfo = new Bguserinfo();
        bguserinfo.setId(id);
        boolean b = bguserinfoService.deleteById(id);
        if (b) {
            return renderSuccess("删除成功！");
        } else {
            return renderError("删除失败！");
        }
    }
    
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, Long id) {
        Bguserinfo bguserinfo = bguserinfoService.selectById(id);
        model.addAttribute("bguserinfo", bguserinfo);
        return "admin/bguserinfo/bguserinfoEdit";
    }
    
    /**
     * 编辑
     * @param 
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(@RequestParam MultipartFile[] myfiles, HttpServletRequest request,@Valid Bguserinfo bguserinfo) {
    	try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String pathRoot = request.getSession().getServletContext().getRealPath("");
			SimpleDateFormat sf=new SimpleDateFormat("yyyyMMdd");
			String datestr=sf.format(new Date());
			// 头像
			String path="";
			MultipartFile file = multipartRequest.getFile("pic_manPhoto");
			if(file != null && file.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-","");  
				//获得文件类型（可以判断如果不是图片，禁止上传）  
	            String contentType=file.getContentType();  
	            //获得文件后缀名称  
	            String imageName=contentType.substring(contentType.indexOf("/")+1);  
	            path="/upload/images/"+datestr+"/"+uuid+"."+imageName;
	            File tFile=new File(pathRoot+path);
	            if(!tFile.getParentFile().exists()){
	            	tFile.mkdirs();
	            }
	            file.transferTo(tFile);  				  
	            bguserinfo.setPreview(path);
			}
			bguserinfo.setAddtime(new Date());
	        bguserinfo.setUpdatetime(new Date());
	        boolean b = bguserinfoService.updateById(bguserinfo);
	        if (b) {
	            return renderSuccess("编辑成功！");
	        } else {
	            return renderError("编辑失败！");
	        }
		} catch (Exception e) {
			e.printStackTrace();
			 return renderError("编辑失败！"+e.getMessage());
		}
    }
    
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/viewPage")
    public String viewPage(Model model, Long id) {
        Bguserinfo bguserinfo = bguserinfoService.selectById(id);
        model.addAttribute("bguserinfo", bguserinfo);
        return "admin/bguserinfo/bguserinfoView";
    }
    
}
